package com.atguigu.admin.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 目标方法执行之前
     * 1、配置好拦截器，拦截器要拦截哪些请求
     * 2、把这些配置放在容器中
     * @param request current HTTP request
     * @param response current HTTP response
     * @param handler chosen handler to execute, for type and/or instance evaluation
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestURI = request.getRequestURI();
        log.info("preHandle拦截的请求：{}", requestURI);
        Object user = request.getSession().getAttribute("loginUser");
        if (user == null) {

            request.setAttribute("msg", "请先登录");
            //response.sendRedirect("/login");
            request.getRequestDispatcher("/login").forward(request, response);
            return false;
        }
        return true;

    }

    /**
     * 请求处理完成之后(页面渲染之后)
     * @param request current HTTP request
     * @param response current HTTP response
     * @param handler the handler (or {@link HandlerMethod}) that started asynchronous execution, for type and/or instance analysis
     * @param ex any exception thrown on handler execution, if any; this does not include exceptions that have been handled through an exception resolver
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion 执行，异常有：{}", ex);
    }

    /**
     * 目标方法执行之后
     * @param request current HTTP request
     * @param response current HTTP response
     * @param handler the handler (or {@link HandlerMethod}) that started asynchronous execution, for type and/or instance analysis
     * @param modelAndView the {@code ModelAndView} that the handler returned (can also be {@code null})
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle 执行{}", modelAndView);
    }
}
